package com.atguigu.bigdata.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bigdata.gmall.realtime.app.BaseAppV1;
import com.atguigu.bigdata.gmall.realtime.bean.TrafficHomeDetailPageViewBean;
import com.atguigu.bigdata.gmall.realtime.common.Constant;
import com.atguigu.bigdata.gmall.realtime.util.AtguiguUtil;
import com.atguigu.bigdata.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2022/10/17 10:58
 */
public class Dws_03_DwsTrafficPageViewWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_03_DwsTrafficPageViewWindow().init(
            4003,
            2,
            "Dws_03_DwsTrafficPageViewWindow",
            Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        // 1. 过滤首页和详情页记录
        SingleOutputStreamOperator<JSONObject> homeAndDetailStream = filterHomeAndDetail(stream);
        // 2. 转成一个 pojo
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> beanStream = parseToPojo(homeAndDetailStream);
        // 3. 开窗聚和
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> resultStream = windowAndAgg(beanStream);
        
        // 4. 写出到 clickhouse 中
        writeToClickHouse(resultStream);
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_traffic_page_view_window", TrafficHomeDetailPageViewBean.class));
    }
    
    private SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> windowAndAgg(
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> beanStream) {
        return beanStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TrafficHomeDetailPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
            )
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TrafficHomeDetailPageViewBean>() {
                    @Override
                    public TrafficHomeDetailPageViewBean reduce(TrafficHomeDetailPageViewBean b1,
                                                                TrafficHomeDetailPageViewBean b2) throws Exception {
                        b1.setHomeUvCt(b1.getHomeUvCt() + b2.getHomeUvCt());
                        b1.setGoodDetailUvCt(b1.getGoodDetailUvCt() + b2.getGoodDetailUvCt());
                        return b1;
                    }
                },
                new ProcessAllWindowFunction<TrafficHomeDetailPageViewBean, TrafficHomeDetailPageViewBean, TimeWindow>() {
                    @Override
                    public void process(Context ctx,
                                        Iterable<TrafficHomeDetailPageViewBean> elements,
                                        Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                        TrafficHomeDetailPageViewBean bean = elements.iterator().next();
                        
                        bean.setStt(AtguiguUtil.toDatTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.toDatTime(ctx.window().getEnd()));
    
                        bean.setTs(System.currentTimeMillis());
                        
                        out.collect(bean);
                    }
                }
            );
    }
    
    private SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> parseToPojo(
        SingleOutputStreamOperator<JSONObject> steam) {
        return steam
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
            .process(new KeyedProcessFunction<String, JSONObject, TrafficHomeDetailPageViewBean>() {
                
                private ValueState<String> homeState;
                private ValueState<String> goodDetailState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    homeState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<String>("homeState", String.class));
                    goodDetailState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<String>("goodDetailState", String.class));
                }
                
                @Override
                public void processElement(JSONObject value,
                                           Context ctx,
                                           Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                    Long ts = value.getLong("ts");
                    String pageId = value.getJSONObject("page").getString("page_id");
                    
                    String today = AtguiguUtil.toDate(ts);
                    
                    long homeUvCt = 0L;
                    String homeDate = homeState.value();
                    
                    if ("home".equals(pageId) && !today.equals(homeDate)) {
                        homeUvCt = 1L;
                        // 更新状态
                        homeState.update(today);
                    }
                    
                    long goodDetailUvCt = 0L;
                    String goodDetailDate = goodDetailState.value();
                    if ("good_detail".equals(pageId) && !today.equals(goodDetailDate)) {
                        goodDetailUvCt = 1L;
                        // 更新状态
                        goodDetailState.update(today);
                    }
                    
                    TrafficHomeDetailPageViewBean bean = new TrafficHomeDetailPageViewBean("", "", homeUvCt, goodDetailUvCt, ts);
                    //System.out.println(homeUvCt + "  " + goodDetailUvCt);
                    if (homeUvCt + goodDetailUvCt == 1) {
                        out.collect(bean);
                    }
                }
            });
    }
    
    private SingleOutputStreamOperator<JSONObject> filterHomeAndDetail(DataStreamSource<String> stream) {
        return stream
            .map(JSON::parseObject)
            .filter(new FilterFunction<JSONObject>() {
                @Override
                public boolean filter(JSONObject obj) throws Exception {
                    String pageId = obj.getJSONObject("page").getString("page_id");
                    return "home".equals(pageId) || "good_detail".equals(pageId);
                }
            });
    }
}
/*

非并行算子:
    1. 没有 keyBy 开窗, 窗口处理函数
    2. socket source
-----
流量域页面浏览各窗口汇总表
    统计当日的首页和商品详情页独立访客数。
 
 1. 首页的独立访客数
 
 2. 详情页的独立访客数
 
数据源:
    dwd 层页面日志
    
过滤:
    过滤出首页和详情页记录
    
keyBy: 按照 mid 分组, 同一个设备的访问记录再一起

处理: 找到这个 mid 的第一条首页访问记录
     找到这个 mid 的第一条详情页访问记录
     
     用: 状态.

开窗聚合:
    不用 keyBy
    windowAll
    
写出到clickhouse 中


 */